var router = require('koa-router')({ prefix: '/project/:id/centerConfig' });
var models = require('./../../../models');
var q = require('q');
router.get('/', function* (next) {
    // var centers = yield this.state.project.getManualCenters();
    var manualCenters = yield models.ManualCenter.findAll({
        where: {
            prjId: this.state.project.id
        }
    });
    var designCenters = yield models.DesignCenter.findAll({
        where: {
            prjId: this.state.project.id
        }
    });


    this.render('project/center.config.jade', {
        url: this.request.url,
        manualCenters: manualCenters,
        designCenters: designCenters
    });
});

router.get('/deleteAll/:centerType', function* (next) {
    var model = this.params.centerType === 'manual' ? models.ManualCenter : models.DesignCenter;
    yield model.destroy({
        where: {
            prjId: this.state.project.id
        }
    });
    this.redirect(`/project/${this.params.id}/centerConfig`);

});

router.post('/', function* (next) {
    var filePath = this.request.body.files.file.path;
    var Converter = require("csvtojson").Converter;
    var converter = new Converter({
        noheader: true,
        headers: ["e", "n", "h", "mileage"]
    });
    var centerArray = [];
    var promise = (function onReadComplete() {
        var defer = q.defer();
        //end_parsed will be emitted once parsing finished 
        converter.on("end_parsed", function (jsonArray) {

            centerArray = jsonArray;
            defer.resolve();
        });
        return defer.promise;
    })();
    //read from file 
    require("fs").createReadStream(filePath).pipe(converter);

    yield promise;
    var prjId = this.state.project.id;
    centerArray = centerArray.map(function (item) {
        return Object.assign({ prjId: prjId }, item);
    });
    var model = this.request.body.fields.centerType === 'manual' ? models.ManualCenter : models.DesignCenter;
    yield model.bulkCreate(centerArray);
    this.redirect(this.request.url);
});
module.exports = router.routes();
